package com.writing.controller;

import com.writing.common.Result;
import com.writing.service.VoiceGenerationService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * 语音合成控制器
 */
@RestController
@RequestMapping("/voice")
@RequiredArgsConstructor
public class VoiceGenerationController {

    private final VoiceGenerationService voiceGenerationService;

    /**
     * 生成语音
     */
    @PostMapping("/synthesis")
    public Result<VoiceGenerationResponse> generateVoice(@RequestBody @Valid VoiceGenerationRequest request,
                                                          HttpServletRequest httpRequest) {
        Long userId = (Long) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.unauthorized("用户未登录");
        }

        try {
            VoiceGenerationResponse response = voiceGenerationService.generateVoice(request, userId);
            return Result.success("语音合成成功", response);
        } catch (Exception e) {
            return Result.error("语音合成失败: " + e.getMessage());
        }
    }

    /**
     * 语音合成请求DTO
     */
    @Data
    public static class VoiceGenerationRequest {
        @NotBlank(message = "模型名称不能为空")
        private String model;

        @NotBlank(message = "合成文本不能为空")
        private String text;

        private String voice;

        @NotNull(message = "音频格式不能为空")
        private String format = "mp3";

        @NotNull(message = "采样率不能为空")
        private Integer sampleRate = 24000;

        private Boolean useSSML = false;
    }

    /**
     * 语音合成响应DTO
     */
    @Data
    public static class VoiceGenerationResponse {
        private VoiceData data;
    }

    @Data
    public static class VoiceData {
        private String url;
        private String b64Json;
        private Double duration;
    }
}

